package com.xiaoxin.common;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description:
 * @Author TongRui
 * @Date 2021/11/22
 * @Version V1.0
 **/
@Slf4j
public class MyIdentifierGenerator implements IdentifierGenerator {

    private final Sequence sequence;
    private DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern("yyyyMMddHH");

    public MyIdentifierGenerator(InetAddress inetAddress) {
        this.sequence = new Sequence(inetAddress);
    }

    public MyIdentifierGenerator(long workerId, long dataCenterId) {
        this.sequence = new Sequence(workerId, dataCenterId);
    }

    public MyIdentifierGenerator(Sequence sequence) {
        this.sequence = sequence;
    }

    @Override
    public Long nextId(Object entity) {
        // 雪花算法的前8位，替换成年月日时（其中年采用2位计算）
        String yyMonth = LocalDateTime.now().format(dtFormatter).substring(2);
        String str = yyMonth.concat(String.valueOf(sequence.nextId()).substring(8));
        return Long.parseLong(str);
    }

}